import { Handlers } from "$fresh/server.ts";
import { getDbClient } from "../../../utils/db.ts";
import { AdminState } from "../../_middleware.ts";

export const handler: Handlers<null, AdminState> = {
  async POST(req, ctx) {
    // 检查管理员权限
    if (!ctx.state.isAdmin) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { "Content-Type": "application/json" }
      });
    }

    try {
      const form = await req.formData();
      const title = form.get("title") as string;
      const content = form.get("content") as string;

      // 简单验证
      if (!title || !content) {
        return new Response(JSON.stringify({ error: "Title and content are required" }), {
          status: 400,
          headers: { "Content-Type": "application/json" }
        });
      }

      // 插入数据库
      const client = await getDbClient();
      try {
        const result = await client.execute(
          "INSERT INTO posts (title, content) VALUES (?, ?)",
          [title, content]
        );

        const postId = result.lastInsertId;

        // 重定向到新创建的文章
        const headers = new Headers();
        headers.set("Location", `/posts/${postId}`);
        return new Response(null, {
          status: 303,
          headers
        });
      } finally {
        await client.close();
      }
    } catch (error) {
      console.error("Error creating post:", error);
      return new Response(JSON.stringify({ error: "Failed to create post" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
}; 